#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdlib>

void WaitAll(int sig)
{
    while (1) // 这里循环是为了有多个子进程需要回收的情况
    {
        pid_t n = waitpid(-1, nullptr, WNOHANG); // WNOHANG让父进程不阻塞在waitpid这里
        if (n == 0)
        {
            break;
        }
        else if (n < 0)
        {
            std::cout << "wait error" << std::endl;
            break;
        }

        std::cout << "father get a signal:" << sig << std::endl;
    }
}

int main()
{
    signal(SIGCHLD, WaitAll);
    // signal(SIGCHLD, SIG_IGN);//将SIGCHLD的处理动作设置为SIG_IGN,子进程在退出时会自动清理，不会出现僵尸

    for (int i = 0; i < 5; i++)
    {
        pid_t id = fork();
        if (id == 0)
        {
            sleep(3);
            std::cout << "child process exit" << std::endl;
            if (i <= 3)
            {
                exit(3);
            }
            else
            {
                pause();
            }
            // exit(3);
        }
    }

    while (1)
    {
        std::cout << "father process exit" << std::endl;
        sleep(1);
    }
    return 0;
}